package com.mymarkdown.app.fx.event.hander.impl;

import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.assemblys.FxTreeItem;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.ModifyWindow;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;
import java.util.Optional;

/**
 * @author ：zenglun
 * @date ：Created in 2021/12/25 12:22 PM
 * @description： 删除文件事件
 * @modified By：
 * @version: $
 */
@Slf4j
@KeyWord(FxEventEnum.DELETE_FILE_EVENT)
@Component
public class DeleteFileMenuHandlerImpl implements KeyWordHandler {

    private FxTreeItem<String> fxTreeItem;

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;

    @Autowired
    private ModifyWindow modifyWindow;

    @Override
    public void handler(WebEngine engine, FxEvent event) {
        File sourceFile = fxTreeItem.getSourceFile();
        //先删除文件
        if (sourceFile.delete()){
            //先获取父节点的TreeItem
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("删除成功!"));
        }else{
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("删除失败!"));
        }
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        FxTreeItem<String> fxTreeItem = (FxTreeItem<String>)event.getTarget();
        if (Objects.isNull(fxTreeItem)){
            return false;
        }
        File sourceFile = fxTreeItem.getSourceFile();
        if (Objects.isNull(sourceFile) || !sourceFile.exists()){
            return false;
        }
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("删除文件");
        alert.setHeaderText("");
        alert.setContentText("是否真的删除文件,删除之后文件不可恢复?");
        Optional<ButtonType> buttonType = alert.showAndWait();
        if (buttonType.orElse(null) == ButtonType.OK){
            this.fxTreeItem = fxTreeItem;
            return true;
        }
        return false;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }
}
